<template>
  <el-container class="chat-page">
    <el-main>
      <message-list :messages="messages" ref="messageListRef" />
    </el-main>
    <el-footer class="chat-footer">
      <chat-input @send="handleSendMessage" />
    </el-footer>
  </el-container>
</template>

<script>
import { ref, watch, onMounted } from "vue";
import { useRoute } from "vue-router"; // 新增导入
import ChatInput from "@/components/ChatInput.vue";
import MessageList from "@/components/MessageList.vue";
import { useChatStore } from "@/stores/chat";

export default {
  components: {
    ChatInput,
    MessageList,
  },
  setup() {
    const chatStore = useChatStore();
    const messages = ref([]);
    const route = useRoute(); // 初始化路由

    // 新增：监听URL参数变化
    watch(
      () => route.query.projectId,
      async (newProjectId) => {
        if (newProjectId && newProjectId !== String(chatStore.projectId)) {
          console.log("URL参数变化，切换项目ID:", newProjectId);
          await chatStore.switchProject(Number(newProjectId));
        }
      },
      { immediate: true } // 初始加载时执行
    );

    // 确保在组件挂载时加载当前会话消息
    onMounted(async () => {
      console.log("[ChatView] 组件挂载，初始化ChatStore");

      // 初始化ChatStore（包括BroadcastChannel监听）
      try {
        await chatStore.init();
        console.log("[ChatView] ChatStore初始化完成");
      } catch (error) {
        console.error("[ChatView] ChatStore初始化失败:", error);
      }

      // 先加载会话列表
      try {
        await chatStore.fetchChatList();
        console.log("[ChatView] 会话列表加载完成");
      } catch (error) {
        console.error("[ChatView] 会话列表加载失败:", error);
      }

      // 如果已有消息，直接使用
      if (chatStore.messages.length > 0) {
        messages.value = chatStore.messages;
        console.log(
          "[ChatView] 使用现有消息，数量:",
          chatStore.messages.length
        );
        return;
      }

      // 否则重新加载消息
      if (chatStore.chatId) {
        await chatStore.fetchMessages(chatStore.chatId);
        messages.value = chatStore.messages;
        console.log(
          "[ChatView] 重新加载消息完成，数量:",
          chatStore.messages.length
        );
      } else if (chatStore.chatList.length > 0) {
        // 如果没有当前会话ID，选择第一个会话
        const firstChatId = chatStore.chatList[0].chatId;
        await chatStore.selectChat(firstChatId);
        messages.value = chatStore.messages;
        console.log(
          "[ChatView] 自动选择第一个会话，消息数量:",
          chatStore.messages.length
        );
      }

      console.log("[ChatView] 组件初始化完成");
    });

    // 监听projectId变化，自动重新加载数据
    watch(
      () => chatStore.projectId,
      async (newProjectId, oldProjectId) => {
        if (newProjectId !== oldProjectId) {
          console.log(
            `[ChatView] 检测到projectId变化: ${oldProjectId} -> ${newProjectId}`
          );

          // 重新加载会话列表
          try {
            await chatStore.fetchChatList();
            console.log("[ChatView] projectId变化后重新加载会话列表完成");
          } catch (error) {
            console.error(
              "[ChatView] projectId变化后重新加载会话列表失败:",
              error
            );
          }

          // 重置消息
          messages.value = chatStore.messages;
        }
      }
    );

    // 监听消息变化
    watch(
      () => chatStore.messages,
      (newMessages) => {
        messages.value = newMessages;
        console.log(
          "[ChatView] 消息列表更新，当前消息数量:",
          newMessages.length
        );
      }
    );

    const handleSendMessage = async (message) => {
      const chatId = chatStore.chatId;
      const language = 0;

      const messagePayload = {
        chatId,
        language,
        msg: message,
      };

      await chatStore.sendMessageToChatGPT(messagePayload);
    };

    return {
      messages,
      handleSendMessage,
    };
  },
};
</script>

<style scoped>
/* 保持原有样式不变 */
.chat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow-x: hidden;
}

.el-main {
  flex: 1;
  padding: 60px 30px 10px 30px;
  overflow-y: auto;
  position: relative;
  z-index: 10;
  box-sizing: border-box;
  overflow-x: hidden;
}

.chat-footer {
  position: relative;
  padding: 5px 0 10px;
  background: transparent;
  z-index: 100;
  box-shadow: none;
}

@media (max-width: 768px) {
  .el-main {
    padding: 40px 15px 5px 15px;
  }

  .chat-footer {
    padding: 2px 0 5px;
  }
}
</style>